//
//  KLCurrencyPickerSearchResultController.m
//  KLCurrency
//
//  Created by apple on 2017/12/25.
//  Copyright © 2017年 bonc. All rights reserved.
//

#import "KLCurrencyPickerSearchResultController.h"

#import "KLCurrencyEntity.h"
#import "KLCurrencyService.h"
#import "KLCurrencyPickerCell.h"
#import "KLPlistHelper.h"

static const CGFloat searchTextFieldHeight = 30.0f;
static const CGFloat searchTextFieldOffsetX = 10.0f;
static const CGFloat searchTextFieldWidthScale = 0.8f;
static const CGFloat searchTextFieldFontSize = 14.0f;

@interface KLCurrencyPickerSearchResultController () <UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UITextField *searchTextField;
@property (strong, nonatomic) UIButton *cancelButton;
@property (strong, nonatomic) UITableView *tableView;
@property (copy, nonatomic) NSArray <KLCurrencyEntity *>*searchResults;
@property (assign, nonatomic) CGFloat keyboardHeight;

@end

@implementation KLCurrencyPickerSearchResultController

- (UITableView *)tableView {
    if (_tableView == nil) {
        CGRect rect = CGRectMake(0, CGRectGetMaxY(_searchTextField.frame) + 5, self.view.frame.size.width, self.view.frame.size.height - CGRectGetMaxY(_searchTextField.frame) - _keyboardHeight);
        _tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableFooterView = [UIView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
        [self.view addSubview:_tableView];
        
        //注册cell
        [_tableView registerNib:[UINib nibWithNibName:@"KLCurrencyPickerCell" bundle:nil] forCellReuseIdentifier:@"picker"];
        
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
}

- (void)setupUI {
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, searchTextFieldHeight, searchTextFieldHeight)];
    UIImageView *searchImage = [[UIImageView alloc] initWithFrame:CGRectMake(searchTextFieldHeight * 0.25, searchTextFieldHeight * 0.25, searchTextFieldHeight * 0.5, searchTextFieldHeight * 0.5)];
    [searchImage setImage:[UIImage imageNamed:@"search"]];
    [leftView addSubview:searchImage];
    
    self.searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(searchTextFieldOffsetX, searchTextFieldHeight, (self.view.frame.size.width - searchTextFieldOffsetX) * searchTextFieldWidthScale, searchTextFieldHeight)];
    self.searchTextField.placeholder = @"请出入货币名称或者缩写";
    self.searchTextField.leftView = leftView;
    self.searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.searchTextField.leftViewMode = UITextFieldViewModeAlways;
    self.searchTextField.backgroundColor = [UIColor whiteColor];
    self.searchTextField.borderStyle = UITextBorderStyleRoundedRect;

//    self.searchTextField.layer.cornerRadius = 3.0f;
    self.searchTextField.font = [UIFont systemFontOfSize:searchTextFieldFontSize];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    
    self.cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width * (1 - searchTextFieldWidthScale), searchTextFieldHeight)];
    self.cancelButton.center = CGPointMake(CGRectGetMaxX(_searchTextField.frame) + _cancelButton.frame.size.width / 2, _searchTextField.center.y);
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelButton setTitleColor:UIColorFromRGB(0x99A4BF) forState:UIControlStateNormal];
    [self.cancelButton.titleLabel setFont:[UIFont systemFontOfSize:searchTextFieldFontSize + 3]];
    [self.cancelButton addTarget:self action:@selector(cancelSearchAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_searchTextField];
    [_searchTextField becomeFirstResponder];
    [self.view addSubview:_cancelButton];

}

- (void)cancelSearchAction:(UIButton *)button {
    [_searchTextField resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)keyboardDidShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    CGRect rect = [(NSValue *)[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.keyboardHeight = rect.size.height;
}

- (void)searchTextDidChange:(NSNotification *)notification {
    UITextField *textField = notification.object;
    if (textField.text.length > 0) {
        [KLCurrencyService getFilteredCurrencyEntitiesWithSearchText:textField.text completion:^(NSArray<KLCurrencyEntity *> *searchResults) {
            self.searchResults = searchResults;
            [self.tableView reloadData];
        } failure:^(NSString *error) {
            self.searchResults = nil;
            [self.tableView reloadData];
        }];
    } else {
        self.searchResults = nil;
        [self.tableView reloadData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchResults.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KLCurrencyEntity *currency = self.searchResults[indexPath.row];
    KLCurrencyPickerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"picker"];
    if ([currency.abbreviation isEqualToString:self.changeCurrencyEntity.abbreviation]) {
        currency.changing = YES;
    } else {
        currency.changing = NO;
    }
    cell.currencyEntity = currency;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //取出选中模型
    KLCurrencyEntity *currency = self.searchResults[indexPath.row];
    [self filteredCurrencyDidSelected:currency];
}

- (void)filteredCurrencyDidSelected: (KLCurrencyEntity *)currency {
    if ([self.delegate respondsToSelector:@selector(chosenFilteredCurrency:)]) {
        [_searchTextField resignFirstResponder];
        [self dismissViewControllerAnimated:YES completion:nil];
        [self.delegate chosenFilteredCurrency:currency];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
